# encoding: utf-8

class Account
  include Mongoid::Document

  field :access_token_weibo,    :type => String
  field :code,                  :type => String
  field :uid,                   :type => String

  field :access_token_tencent,  :type => String
  field :openid,                :type => String
  field :openkey,               :type => String

  field :auth_key,              :type => String
  field :oops_id,               :type => String
  field :oops_role,             :type => String

  field :send_count,            :type => Hash

  field :max_send_count_h,      :type => Integer, :default => 60

  field :level,                 :type => Integer, :default => 1

  has_one :reply, :class_name => "Statistics::Reply"
  has_many :tasks
  has_many :push_histories

  delegate :new, :to => :tasks, :prefix => true

  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是类方法
  #
  # # # # # # # # # # # # # # # #

  def self.access_weibo(code)
    # 目前只有新浪
    data = {
      'client_id'     => Oauth2::WEIBO_CLIENT_ID,
      'client_secret' => Oauth2::WEIBO_CLIENT_SECRET ,
      'grant_type'    => 'authorization_code',
      'redirect_uri'  => Oauth2::WEIBO_CALLBACK_URL,
      'code'          => code}
    result = Utility.post_j 'https://api.weibo.com/oauth2/access_token', data
    if result["uid"]
      if uw = Utility::Weibo.where(:uid => result["uid"]).first
        uw.access_token = result["access_token"]
        uw.expires_in   = Time.now + result["expires_in"].to_i
        uw.status.each do |k, v|
          uw.status[k] = true
        end
        uw.access_time = Time.now
        return uw.save, "admin"
      else
        account = Account.find_or_create_by(:uid => result["uid"])
        account.access_token_weibo = result["access_token"]
        return account.save, account._id
      end
    else
      return false, result
    end
  end

  def self.access_tencent(code)
    data = {
      'client_id'     => Oauth2::TENCENT_CLIENT_ID,
      'client_secret' => Oauth2::TENCENT_CLIENT_SECRET ,
      'grant_type'    => 'authorization_code',
      'redirect_uri'  => Oauth2::TENCENT_CALLBACK_URL,
      'code'          => code
    }
    result = Utility.get_q('https://open.t.qq.com/cgi-bin/oauth2/access_token', data)
    uw = Utility::Tencent.find_or_create_by(:uid => result['openid'])
    uw.access_token = result['access_token']
    uw.status.each do |k, v|
      uw.status[k] = true
    end
    uw.access_time = Time.now
    uw.refresh_token = result['refresh_token']
    if uw
      return uw.save, "admin"
        # account = Account.find_or_create_by('openid' => result['openid'])
        # account.access_token_tencent = result['access_token']
        # return account.save, account._id
    else
      return false, result
    end
  end

  def self.auto_accessing(sns_type, ids)
    Sidekiq.redis do |redis|
     if pid = redis.get("flowy:auto_access:#{sns_type}")
        return pid
      else
        ::AutoAccessWorker.perform_async(ids || Utility::Weibo.active.map(&:_id).join(','), sns_type)
      end
    end
  end

  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是对外开放的接口
  #
  # # # # # # # # # # # # # # # #

  def gaps
    7.days
  end

  #####  Weibo  #####

  def create_comment_weibo(comment, mid, uid)
    logger.info "========== 准备发送 =========="
    result = {}
    # 关于 post_j 要做效率和鲁棒上的优化
    if oops_role == "admin"
      logger.info ">发送状态: 以管理员身份发送"
      result = Utility::Weibo.get_spammer("create_comment") do |spammer|
        spammer.create_comment(comment, mid, uid)
      end
    else
      result = Utility.post_j 'https://api.weibo.com/2/comments/create.json', {
        :access_token => self.access_token_weibo,
        :comment => comment,
        :id => mid,
        :comment_ori => 0
      }
    end
    # if result["user"]
    #   user = Statistics::SnsUser.find_or_create_by(:uid => result["status"]["user"]['id'])
    #   user.update_recent
    #   logger.info ">发送状态: 对--#{result["status"]["user"]["screen_name"]}--的评论发送成功"
    # end
    logger.info "========== 发送完毕 =========="
    return result
  end

  def create_comment_tencent(commnet, mid, uid)
    logger.info "========== 准备发送 =========="
    if oops_role =="admin"
      logger.info ">发送状态: 以管理员身份发送"
      result = Utility::Tencent.get_spammer("create_comment") do |spammer|
        spammer.create_comment(commnet, mid, uid)
      end
    else
      result = Utility.post_j 'https://open.t.qq.com/api/t/comment', {
        # 暂时先不写了吧?

      }
    end
  end

  def pick_up_task(params)
    self.tasks.pick_up(params)
  end

  def refresh_replies
    unless self.reply
      self.reply = Statistics::Reply.create(:account_id => self.id)
    end
    self.reply.refresh
  end


  # def user_validate_weibo(user)
  #   return false unless user
  #   return true if user["id"].nil? || user["id"].empty?
  #   wuser = Statistics::WeiboUser.where(:uid => user["id"]).first
  #   if wuser && (Time.now - wuser.recent_sent < gaps)
  #     logger.info ">查询状态: 用户#{user["screen_name"]}被防打扰机制屏蔽"
  #     return false
  #   # else
  #   #   Statistics::WeiboUser.create(:uid => user["id"])
  #   #   return true
  #   end
  #   return true
  # end

  # def get_weibo(weibo_id)
  #   Utility.get_j 'https://api.weibo.com/2/statuses/show.json', {
  #     "access_token" => self.access_token_weibo,
  #     "id" => weibo_id,
  #     }
  #   # {"created_at"=>"Thu Mar 07 09:21:46 +0800 2013", "id"=>3553145265354718, "mid"=>"3553145265354718", "idstr"=>"3553145265354718", "text"=>"国内绝大多数程序员可能就知道个OOP，借着javascript的兴起可能有小部分人能够对原型有所了解，像prolog这样的“奇特”语言能有所了解有所接触的可说是万中无一。 《七周七语言》这本书最大的价值在于让你知道：“原来世界上还有这样一种语言，是基于这样的概念的啊” ……http://t.cn/zYEStzf", "source"=>"<a href=\"http://app.weibo.com/t/feed/4PaMVH\" rel=\"nofollow\">加网分享按钮</a>", "favorited"=>false, "truncated"=>false, "in_reply_to_status_id"=>"", "in_reply_to_user_id"=>"", "in_reply_to_screen_name"=>"", "thumbnail_pic"=>"http://ww1.sinaimg.cn/thumbnail/9692b10djw1e2gy7hlbwwj.jpg", "bmiddle_pic"=>"http://ww1.sinaimg.cn/bmiddle/9692b10djw1e2gy7hlbwwj.jpg", "original_pic"=>"http://ww1.sinaimg.cn/large/9692b10djw1e2gy7hlbwwj.jpg", "geo"=>nil, "user"=>{"id"=>2526195981, "idstr"=>"2526195981", "screen_name"=>"图灵社区", "name"=>"图灵社区", "province"=>"11", "city"=>"5", "location"=>"北京 朝阳区", "description"=>"图灵电子书上线啦，赶快来看看 http://www.ituring.com.cn/book/ebook?sort=all", "url"=>"http://www.ituring.com.cn/", "profile_image_url"=>"http://tp2.sinaimg.cn/2526195981/50/40005235120/0", "profile_url"=>"ituring", "domain"=>"ituring", "weihao"=>"", "gender"=>"f", "followers_count"=>8015, "friends_count"=>596, "statuses_count"=>1080, "favourites_count"=>12, "created_at"=>"Mon Dec 12 14:42:49 +0800 2011", "following"=>false, "allow_all_act_msg"=>false, "geo_enabled"=>true, "verified"=>true, "verified_type"=>5, "remark"=>"", "allow_all_comment"=>false, "avatar_large"=>"http://tp2.sinaimg.cn/2526195981/180/40005235120/0", "verified_reason"=>"图灵社区(ituring.com.cn)官方微博", "follow_me"=>false, "online_status"=>1, "bi_followers_count"=>276, "lang"=>"zh-cn", "star"=>0, "mbtype"=>0, "mbrank"=>0, "block_word"=>0}, "reposts_count"=>12, "comments_count"=>2, "attitudes_count"=>0, "mlevel"=>0, "visible"=>{"type"=>0, "list_id"=>0}}
  # end

  def is_admin?
    oops_role == "admin"
  end

end